#pragma once
#include<unordered_map>
#include"util.hpp"
#include<sstream>

namespace cloud {
	class DataManager {
	private:
		std::string _back_file;
		std::unordered_map<std::string, std::string> _table;
	public:
		DataManager(const std::string& backup_file) :_back_file(backup_file) { InitLoad(); }

		bool Storage()
		{
			std::stringstream ss;
			auto it = _table.begin();
			for (; it != _table.end(); it++)
			{
				ss << it->first << " " << it->second << "\n";
			}

			FileUtil fu(_back_file);
			fu.SetContent(ss.str());
			return true;
		
		

		}
		int spit(const std::string& str, const std::string& sep, std::vector<std::string>* array)
		{
			int count = 0;
			size_t pos = 0, idx = 0;
			while (1)
			{
				pos = str.find(sep, idx);
				if (pos == std::string::npos)
				{
					break;

				}
				if (pos == idx) {
					idx = pos + sep.size();
					continue;
					

				}

				std::string tmp = str.substr(idx, pos - idx);
				array->push_back(tmp);
				count++;
				idx = pos + sep.size();
			}
			if (idx < str.size())
			{
				array->push_back(str.substr(idx));
				count++;
			}

			return count;

		}
		bool InitLoad()
		{
			FileUtil fu(_back_file);
			std::string body;
			fu.GetContent(&body);
			std::vector<std::string>array;
			spit(body, "\n", &array);
			for (auto& a : array)
			{
				std::vector<std::string>tmp;
				spit(a, " ", &tmp);
				if (tmp.size() != 2)
				{
					continue;
				}
				_table[tmp[0]] = tmp[1];


			}
			return true;
		
		}
		bool Insert(const std::string& key, const std::string& val)
		{
			_table[key] = val;
			Storage();
			return true;
		
		
		}
		bool Update(const std::string& key, const std::string& val)
		{
			_table[key] = val;
			Storage();
			return true;
		
		
		}
	
		bool GetOneByKey(const std::string& key,  std::string* val)
		{
			auto it = _table.find(key);
			if (it == _table.end())
			{
				return false;


			}
			*val=it->second;
			return true;
		
		}
		  







	};










}

